package com.honey.compilation.sql.ddl;

import java.sql.Types;

import com.honey.compilation.sql.SqlConstraint;
import com.honey.compilation.sql.SqlKeyWord;
import com.honey.compilation.sql.SqlType;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;

/**
 * 
 * 默认值 约束 
 * @author Administrator
 *
 */
public class ConstraintDefault extends SqlConstraint{
	
	/** 默认值 */
	private String defaultValue;
	
	/** 列的类型 */
	private SqlType sqlType;

	/**
	 * 构造函数
	 * @param sqlType 默认值的类型,也就是列的类型
	 * @param defaultValue 默认值
	 */
	public ConstraintDefault(SqlType sqlType, String defaultValue  ){
		this.defaultValue =defaultValue ;
		this.sqlType = sqlType;
	}
	
	/**
	 * 构造函数
	 * @param defaultValue 默认值
	 */
	public ConstraintDefault(String defaultValue  ){
		this.defaultValue = defaultValue;
		isStringValue();
	}

	/**
	 * 设定默认值是null
	 */
	public void setDefaultValueIsNull(){
		this.defaultValue = "NULL";
		isNumberValue();
	}

	/**
	 * 设定为数字类型
	 */
	public void isNumberValue(){
		sqlType = new SqlType(Types.INTEGER);
	}
	
	/**
	 * 设定为字符类型
	 */
	public void isStringValue(){
		sqlType = new SqlType(Types.VARCHAR);
	}
	
	/**
	 * 设定默认值是字符空
	 */
	public void setDefaultValueIsEmptyString(){
		this.defaultValue = "";
		isStringValue() ;
	}
	
	/**
	 * 判定是否需要加单引号(数字类型不需要加单引号,字符类型需要加单引号) 
	 * @return
	 */
	private boolean isAddQuote(){
		int jdbcType = sqlType. getJdbctype();
		return jdbcType== Types.INTEGER||
			   jdbcType== Types.BIGINT||
			   jdbcType== Types.DOUBLE||
			   jdbcType== Types.FLOAT||
			   jdbcType== Types.TINYINT||
			   jdbcType== Types.SMALLINT||
			   jdbcType== Types.DECIMAL||
			   jdbcType== Types.NUMERIC||
			   jdbcType== Types.REAL
			   ;
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.core.dom.sql.SqlConstraint#getSQLConstraintType()
	 */
	@Override
	public SQLConstraintType getSQLConstraintType() {
		return SQLConstraintType.DEFAULT;
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.core.dom.CompilationElement#compiledContent(int)
	 */
	@Override
	public CharacterBuilder compiledContent(int indentLevel) {
		CharacterBuilder answer = CharacterBuilderFactory.createC16StringBuilder();
		if(defaultValue != null ){
			if(sqlType == null ||  isAddQuote()){
				answer.append(SqlKeyWord.DEFAULT)
				.append(defaultValue);
			}else{
				answer.append(SqlKeyWord.DEFAULT)
				.append(SqlKeyWord.OPERATION_SINGLE_QUOTES)
				.append(defaultValue)
				.append(SqlKeyWord.OPERATION_SINGLE_QUOTES)
				;
			}
			answer.append(SqlKeyWord.OPERATION_SPACE);
		}
		return answer;
	}	
}
